package com.feng.net.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

/**
 * 主要封装一些进行网络通信的方法
 * @author FENG
 *
 */
public class NetUtils {
	
	CloseableHttpClient closeableClient = null;
	
	HttpClient client = null;
	
	HttpGet get = null;
	HttpPost post = null;
	HttpResponse resp = null;
	
	
	Header header = null;
	HttpEntity httpEntity = null;
	
	public NetUtils(){
		getCloseableClient();
	}
	
	/**
	 * 返回可以关闭的client
	 * @return CloseableHttpClient
	 */
	private CloseableHttpClient getCloseableClient(){
		
		//设置请求参数
		RequestConfig requestConfig = RequestConfig.custom()
				.setSocketTimeout(30000)	//设置请求超时时间
				.setConnectionRequestTimeout(30000)		//设置传输超时时间
				.build();
		
		
		closeableClient = HttpClients.custom()
				.setDefaultRequestConfig(requestConfig)
				.build();
		
		return closeableClient;
		
	}
	
	/**
	 * 自动关闭的client
	 * @return HttpClient
	 */
	private HttpClient getClient(){
		
		client = HttpClients.createDefault();
		
		return client;
		
	}
	
	private void close(){
		
		if(closeableClient != null){
			try {
				closeableClient.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
	/**
	 * 进行post请求
	 * 可以自定义设置头部
	 * 可以进行form表单传值
	 * 
	 * 传入的参数放在map中
	 * 如仅仅是请求，请将map设置为空
	 * 
	 * @param url
	 * @param header
	 * @param requestParameter
	 * @return
	 */
	public CloseableHttpResponse postRequest(String url,Header header,Map<String,String> requestParameter){
		
/*		//将client初始化
		if(closeableClient == null){
			getCloseableClient();
		}*/
		
		
		post = new HttpPost(url);
		
		if( !requestParameter.isEmpty()){
			
			
			List<BasicNameValuePair> formparams = 
					new ArrayList<BasicNameValuePair>();
			
			Set<String> keySet = requestParameter.keySet();
			
			Iterator<String> keyIt = keySet.iterator();
			
			while(keyIt.hasNext()){
				
				String key = keyIt.next();
				
				formparams.add(new BasicNameValuePair(key,requestParameter.get(key)));
				
			}
			
			UrlEncodedFormEntity uef = null;
			try {
				uef = new UrlEncodedFormEntity(formparams, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			post.setEntity(uef);
			
			if(header != null){
				get.setHeader(header);
			}
			
		}
		
		try {
			return closeableClient.execute(post);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
		
	}
	
	/**
	 * get请求，当client已初始化时不开启新的client
	 * 默认不关闭client
	 * 传参请放到url中去
	 * @param url
	 * @param header
	 * @return CloseableHttpResponse
	 */
	public CloseableHttpResponse getRequest(String url,Header header){
		
/*		//将client初始化
		if(closeableClient == null){
			getCloseableClient();
		}
		*/
		get = new HttpGet(url);
		
		if(header != null){
			get.setHeader(header);
		}
		
		try {
			return closeableClient.execute(get);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
		
	}

	
	/**
	 * 获取网页实体
	 * 可以设置头部
	 * 采用get请求
	 * 当获取网页长度时，仅对媒体文件生效
	 * @param url
	 * @param header
	 * @return
	 */
	public HttpEntity getEntity(String url,Header header){
		
		return getRequest(url,header).getEntity();
		
	}
	
	/**
	 * 简单的post获取
	 * @param url
	 * @return
	 */
	public HttpEntity postEntity(String url){
		
		return postRequest(url,null,null).getEntity();
		
	}
	
	/**
	 * 获取网页实体
	 * 通过post
	 * 可以设置参数
	 * @param url
	 * @param header
	 * @param rp
	 * @return
	 */
	public HttpEntity postEntity(String url,Header header,Map<String,String> rp){
		
		return postRequest(url,header,rp).getEntity();
		
	}
	
	/**
	 * 获取网页内容
	 * get请求
	 * utf-8编码
	 * @param url
	 * @param header
	 * @return
	 */
	public String getContext(String url,Header header){
		
		try {
			return EntityUtils.toString(getEntity(url,header), "UTF-8");
		} catch (ParseException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 获取网页文档形式
	 * post请求
	 * 可以设置参数
	 * @param url
	 * @param header
	 * @param rp
	 * @return
	 */
	public String postContext(String url,Header header,Map<String,String> rp){
		
		try {
			EntityUtils.toString(postEntity(url,header,rp), "UTF-8");
		} catch (ParseException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
		
	}
	
	public static void main(String[] args) {
		
		NetUtils nt = new NetUtils();
		
//		HttpEntity he = nt.getEntity("http://image.nationalgeographic.com.cn/2015/1117/20151117051608967.jpg",null);
//		
//		System.out.println(he.);
		
		String ent =  nt.getContext("http://image.nationalgeographic.com.cn/2015/1117/20151117051608967.jpg",null);
		
		System.out.println(ent);
		
	}
	
}
